package com.settlement.system.common.util.common;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.Assert;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Json工具类，底层用的是com.fasterxml.jackson.databind.ObjectMapper
 * @author liuqing
 * @version 0.1.0
 *
 */
public class JsonUtil {

	static final String NOT_NULL_MESSAGE = "转换对象不能为null";
	static final String TYPE_NOT_NULL_MESSAGE = "转换对象类型不能为null";

	private JsonUtil() {
		super();
	}

	/**
	 * 将对象转换成String
	 * 
	 * @param info
	 *            对象
	 * @return
	 * @throws JsonProcessingException
	 */
	public static String writeValueAsString(Object info) throws JsonProcessingException {
		Assert.notNull(info, NOT_NULL_MESSAGE);
		ObjectMapper mapper = new ObjectMapper();
		return mapper.writeValueAsString(info);
	}

	/**
	 * 将String转换成对象
	 * 
	 * @param str
	 *            要转换的String
	 * @param objType
	 *            要转换成对象的类型Class
	 * @return
	 * @throws IOException
	 */
	public static <T> T readValue(String str, Class<T> objType) throws IOException {
		Assert.notNull(str, NOT_NULL_MESSAGE);
		Assert.notNull(objType, TYPE_NOT_NULL_MESSAGE);
		ObjectMapper mapper = new ObjectMapper();
		return mapper.readValue(str, objType);
	}

	/**
	 * 将String转换成List<T>
	 * 
	 * @param str
	 *            要转换的String
	 * @param objType
	 *            要转换成对象的类型Class
	 * @return
	 * @throws IOException
	 */
	public static <T> List<T> readListValue(String str, Class<T> objType) throws IOException {
		Assert.notNull(str, NOT_NULL_MESSAGE);
		Assert.notNull(objType, TYPE_NOT_NULL_MESSAGE);
		ObjectMapper mapper = new ObjectMapper();

		JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class, objType);
		return mapper.readValue(str, javaType);
	}

	/**
	 * 将String转换成Map<String,Object>
	 * 
	 * @param str
	 *            要转换的String
	 * @param objType
	 *            要转换成对象的类型Class
	 * @return
	 * @throws IOException
	 */
	public static <T> Map<String, T> readMapValue(String str, Class<T> objType) throws IOException {
		Assert.notNull(str, NOT_NULL_MESSAGE);
		Assert.notNull(objType, TYPE_NOT_NULL_MESSAGE);
		ObjectMapper mapper = new ObjectMapper();

		JavaType javaType = mapper.getTypeFactory().constructParametricType(HashMap.class, String.class, objType);
		return mapper.readValue(str, javaType);
	}

	/**
	 * 获取对象的JOSN格式,异常后获取对象的toString
	 *
	 * @param info
	 * @return
	 */
	public static String getJsonOrToString(Object info) {
		try {
			return writeValueAsString(info);
		} catch (Exception ex) {
			return info.toString();
		}
	}

}
